﻿using System;
using System.Text.RegularExpressions;
using Liber;
using System.Collections.Generic;
using Liber.BizTools;
using Liber.SOA;
using Liber.ORM;
using Liber.Event;
using System.Xml;

namespace SoBusiness.App
{
    public class PurchaseApp : SOAUnit
    {
        public PurchaseApp(SOAHost _host)
            : base(_host)
        {
            EventBUS.OnBizEvent += EventBUS_OnBizEvent;
        }

        private void EventBUS_OnBizEvent(EventEditor obj)
        {
            if (obj["BizObject"].ToString() == "Account" &&obj["BizAction"].ToString() == "Approve" && (BizObjLifeStatus)obj["BizStatus"]== BizObjLifeStatus.Completed)
            {
                //对于账号审核通过，加入某个企业了,或企业审核通过，扫描匹配他参与的所有订单
                TryMatchAcntOrder((long)obj["ObjID"]);
                PublishOrder(false);
            }
            else if (obj["BizObject"].ToString() == "Company"&& obj["BizAction"].ToString() == "Approve" && (BizObjLifeStatus)obj["BizStatus"] == BizObjLifeStatus.Completed)
            {
                TryMatchCompanyOrder(obj["CompanyName"].ToString(), (long)obj["CompanyOrg"]);
                PublishOrder(false);
            }
            else if (obj["BizObject"].ToString() == "File" && obj["BizAction"].ToString() == "Upload")
            {
                long fid = (long)obj["ObjID"];
                string fname =obj["FileName"].ToString().Split('.')[0].Replace("%ef%bc%9f","？");
                if (fname.IndexOf("？Order-Purchasecontract")>0)
                {
                    //发现上传了订单采购合同文本
                    var fnparted = fname.Split('？');
                    string srcodguid = fnparted[0];
                    var cmd = Host.ORM.DB.PG().Select<Trade>()
                                   .Where("src_orderid").Eq(srcodguid)
                                   .And("iscurrentver").Eq(true);
                    if (fnparted.Length > 2)
                    {
                        string ver = fnparted[2];
                        cmd.And("src_orderversion").Eq(ver);
                    }
                    
                    var order=cmd.Limit(1)
                                 .Query();
                    if (order.Count > 0)
                    {
                        BORelation of = new BORelation("Order-Attachment", fid, (long)order[0]["id"]);
                        Host.ORM.DB.PG().Insert(of)
                                        .Where("").NotExists(Host.ORM.DB.PG().Select<BORelation>()
                                                                             .Where("rtype").Eq("Order-Attachment")
                                                                             .And("srcid").Eq(fid)
                                                                             .And("objid").Eq((long)order[0]["id"]))
                                        .GO();
                    }

                }
            }
            else
            {

            }
        }

        [API("RematchOrder")]
        FnResult<DyObject> CloudAdminRematchOrder(SOARequestContext rq)
        {
            long acnt = rq.RequestContext.GetOrDefault<long>("acnt", -1);
            TryMatchAcntOrder(acnt);
            PublishOrder(false);
            return FnResult<DyObject>.Sucess(null);
        }

        [API("QueryOrder")]
        FnResult<DyObject> QueryOrder(SOARequestContext rq)
        {
            long uid = rq.RequestContext.GetOrDefault<long>("uid", -1);
            bool onlycount = rq.RequestContext.GetOrDefault<bool>("onlycount", false);
            bool onlyMine = rq.RequestContext.GetOrDefault<bool>("onlymine", true);
            string status = rq.RequestContext.GetOrDefault<string>("status", "pending");
            string flag = rq.RequestContext.GetOrDefault<string>("flag", ""); //toDelivery,toPay,toStockIn
            string ordDate = rq.RequestContext.GetOrDefault<string>("ordDate", "recent");  //recent,thisWeek,preWeek,thisMonth
            string dlvDate = rq.RequestContext.GetOrDefault<string>("dlvDate", "all");
            string ordDateStart = rq.RequestContext.GetOrDefault<string>("ordDateStart", "");
            string ordDateEnd = rq.RequestContext.GetOrDefault<string>("ordDateEnd", "");
            string dlvDateStart = rq.RequestContext.GetOrDefault<string>("dlvDateStart", "");
            string dlvDateEnd = rq.RequestContext.GetOrDefault<string>("dlvDateEnd", "");
            string supplier = rq.RequestContext.GetOrDefault<string>("supplier", "");
            string buyer = rq.RequestContext.GetOrDefault<string>("buyer", "");
            string constructor = rq.RequestContext.GetOrDefault<string>("constructor", "");
            int page = rq.RequestContext.GetOrDefault<int>("page", -1);
            int num = rq.RequestContext.GetOrDefault<int>("num", 20);
            string desc = rq.RequestContext.GetOrDefault<string>("desc", "");
            string asc = rq.RequestContext.GetOrDefault<string>("asc", "");

            PGSQLHelper cmd = Host.ORM.DB.PG().Select<Trade>(onlycount ? "count(1) as total" : "").As("od")
                                     .Where("isdeleted").Eq(false) as PGSQLHelper;
            cmd.And("iscurrentver").Eq(true);

            //处理发布时间范围筛选（周日作为一周的开始）
            DateTime ods = DateTime.MinValue;
            DateTime ode = DateTime.MinValue;
            DateTime.TryParse(ordDateStart, out ods);
            DateTime.TryParse(ordDateEnd, out ode);
            if (ods != DateTime.MinValue && ode != DateTime.MinValue)
            {
                cmd.And("src_orderdate").BiggerOrEq(ods)
                    .And("src_orderdate", true).Smaller(ode.AddDays(1));
            }
            else if (ordDate == "thisWeek")
            {
                DateTime dt = DateTime.Today;
                DateTime startWeek = dt.AddDays(0 - Convert.ToInt32(dt.DayOfWeek.ToString("d")));  //本周周日
                DateTime endWeek = startWeek.AddDays(7);  //下周周日  

                cmd.And("src_orderdate").BiggerOrEq(startWeek)
                   .And("src_orderdate", true).Smaller(endWeek);
            }
            else if (ordDate == "preWeek")
            {
                DateTime dt = DateTime.Today;
                DateTime startWeek = dt.AddDays(-7 - Convert.ToInt32(dt.DayOfWeek.ToString("d")));  //上周周日 
                DateTime endWeek = startWeek.AddDays(7);  //本周周日  

                cmd.And("src_orderdate").BiggerOrEq(startWeek)
                    .And("src_orderdate", true).Smaller(endWeek);
            }
            else if (ordDate == "thisMonth")
            {
                DateTime dt = DateTime.Today;
                DateTime startMonth = dt.AddDays(1 - dt.Day);  //本月月初  
                DateTime endMonth = startMonth.AddMonths(1);  //下月第一天  
                cmd.And("src_orderdate").BiggerOrEq(startMonth)
                   .And("src_orderdate", true).Smaller(endMonth);
            }
            else
            {
            }

            //处理发货日期筛选
            DateTime dlvs = DateTime.MinValue;
            DateTime dlve = DateTime.MinValue;
            DateTime.TryParse(dlvDateStart, out dlvs);
            DateTime.TryParse(dlvDateEnd, out dlve);
            if (dlvs != DateTime.MinValue && dlve != DateTime.MinValue)
            {
                cmd.And("deliverydate").BiggerOrEq(dlvs)
                   .And("deliverydate", true).Smaller(dlve.AddDays(1));
            }
            else if (dlvDate == "today")
            {
                DateTime dt = DateTime.Today;
                cmd.And("deliverydate").BiggerOrEq(dt)
                   .And("deliverydate", true).Smaller(dt.AddDays(1));
            }
            else if (dlvDate == "thisWeek")
            {
                DateTime dt = DateTime.Today;
                DateTime startWeek = dt.AddDays(0 - Convert.ToInt32(dt.DayOfWeek.ToString("d")));  //本周周一  
                DateTime endWeek = startWeek.AddDays(7);  //下周一 

                cmd.And("deliverydate").BiggerOrEq(startWeek)
                   .And("deliverydate", true).Smaller(endWeek);
            }
            else if (dlvDate == "nextWeek")
            {
                DateTime dt = DateTime.Today;
                DateTime startWeek = dt.AddDays(7 - Convert.ToInt32(dt.DayOfWeek.ToString("d")));  //下周周一
                DateTime endWeek = startWeek.AddDays(7);  //下下周周一  
                cmd.And("deliverydate").BiggerOrEq(startWeek)
                   .And("deliverydate", true).Smaller(endWeek);
            }
            else { }


            //处理供应商名称
            if (!string.IsNullOrEmpty(supplier))
            {
                cmd.And("src_supplier").Like("%" + supplier + "%");
            }

            //处理采购经办
            if (!string.IsNullOrEmpty(buyer))
            {
                cmd.And("src_buyer").Like("%" + buyer + "%");
            }

            //处理施工单位
            if (!string.IsNullOrEmpty(constructor))
            {
                cmd.And("src_constructor").Like("%" + constructor + "%")
                    .Or("src_subconstructor").Like("%" + constructor + "%");
            }


            //处理数据权限筛选
            if (!onlyMine)
            {
                //模式1：用户在订单所属部门的上级部门中有岗位
                LiberBizHelper.OrgSVC.InUpOrgTree(ref cmd, "@[od.client_deptid]", uid);
            }
            else
            {
                cmd.And("buyer_id").Eq(uid);
            }

            //处理分页
            if (page > 0 && !onlycount)
            {
                cmd.Limit(num)
                    .Offset((page - 1) * num);
            }

            //处理排序
            if (!onlycount)
            {
                if (!string.IsNullOrEmpty(asc))
                {
                    cmd.AscBy(asc == "dlvdate" ? "deliverydate" : "od.createtime");
                }
                if (!string.IsNullOrEmpty(desc))
                {
                    cmd.DescBy(desc == "orderdate" ? "src_orderdate" : "od.createtime");
                }
            }

            //处理关联进度
            if (flag == "toDelivery")
            {
                cmd.And("status").Eq(BizObjLifeStatus.Active)
                   .And("[tp_dlv.amount]").IsNULL()
                   .Or("[tp_dlv.amount]", true).Smaller("@[od.amount]")
                   .And("[tp_stkn.amount]").Smaller("@[od.amount]")
                   .Or("[tp_stkn.amount]", true).IsNULL()
                   .LeftJoin<TradeProcess>(onlycount ? "" : "@.amount as totaldelivery").As("tp_dlv")
                   .Where("orderid").Eq("@[od.id]")
                   .And("processtype").Eq("Delivery")
                   .And("status").Eq(BizObjLifeStatus.Completed)
                   .LeftJoin<TradeProcess>(onlycount ? "" : "@.amount as totalstockin").As("tp_stkn")
                   .Where("orderid").Eq("@[od.id]")
                   .And("processtype").Eq("StockInSum")
                   .And("status").Eq(BizObjLifeStatus.Completed);

            }
            else if (flag == "toStockIn")
            {
                cmd.And("status").Eq(BizObjLifeStatus.Active)
                   .And("[tp_stkn.amount]").Smaller("@[od.amount]")
                   .Or("[tp_stkn.amount]", true).IsNULL()
                   .LeftJoin<TradeProcess>(onlycount ? "" : "@.amount as totaldelivery").As("tp_dlv")
                   .Where("orderid").Eq("@[od.id]")
                   .And("processtype").Eq("Delivery")
                   .And("status").Eq(BizObjLifeStatus.Completed)
                   .LeftJoin<TradeProcess>(onlycount ? "" : "@.amount as totalstockin").As("tp_stkn")
                   .Where("orderid").Eq("@[od.id]")
                   .And("processtype").Eq("StockInSum")
                   .And("status").Eq(BizObjLifeStatus.Completed);
            }
            else if (flag == "toPay")
            {
                //TODO:需要抓取付款进度
            }
            else
            {
                var st = status.ToBizObjLifeStatus();
                if (st != BizObjLifeStatus.Unknow)
                {
                    cmd.And("status").Eq(st);
                }
                cmd.LeftJoin<TradeProcess>(onlycount ? "" : "@.amount as totaldelivery").As("tp_dlv")
                   .Where("orderid").Eq("@[od.id]")
                   .And("processtype").Eq("Delivery")
                   .And("status").Eq(BizObjLifeStatus.Completed)
                   .LeftJoin<TradeProcess>(onlycount ? "" : "@.amount as totalstockin").As("tp_stkn")
                   .Where("orderid").Eq("@[od.id]")
                   .And("processtype").Eq("StockInSum")
                   .And("status").Eq(BizObjLifeStatus.Completed);
            }

            var data = cmd.Query();

            if (!onlycount)
            {
                return FnResult<DyObject>.Sucess(DyObject.FromObjList("Orders", data));
            }
            else
            {
                return FnResult<DyObject>.Sucess(new DyObject().Set("Total", data[0]["total"]));
            }
        }

        [API("NewReceipt")]
        FnResult<DyObject> NewReceipt(SOARequestContext rq)
        {
            long uid = rq.RequestContext.GetOrDefault<long>("uid", -1);
            var data = rq.RequestContext.GetOrDefault<DyObject>("receiptdata", null);
            var mx = data["items"] as List<DyObject>;
            string dlvidstr = data["dlvid"].ToString();
            string ordidstr = data["orderid"].ToString();

            if (mx == null || mx.Count == 0)
            {
                return FnResult<DyObject>.Failure(Name, "RequiredArgs").SetError("items", "empty receipt mx");
            }

            var cmd = Host.ORM.DB.PG() as PGSQLHelper;
            return LiberBizHelper.TradeSVC.NewReceipt(ref cmd, long.Parse(dlvidstr),long.Parse(ordidstr), mx);
        }

        [API("PullNewPurchaseOrder")]
        FnResult<DyObject> NewOpenPurchaseOrder(SOARequestContext cntx)
        {
            long appid = cntx.RequestContext.GetOrDefault<long>("appid",-1);
            string srcData = cntx.RequestContext.GetOrDefault<string>("opendata", "");
            DateTime bt = DateTime.Now;
            try
            {
                if (!string.IsNullOrEmpty(srcData))
                {
                    var data = XMLSetting.LoadFromStr(srcData);
                    XMLSettingItem[] itms = data.All("Item");
                    CreateNewOrderByOpensrc(itms,appid.ToString());
                    data.Dispose();
                    PublishOrder();
                }
                return FnResult<DyObject>.Sucess(null);
            }
            catch(Exception ex)
            {
                return FnResult<DyObject>.Failure(Name, "Exception").SetError("message", ex.Message);
            }
        }

        /// <summary>
        /// 开放给外部接口用于更新订单入库进度
        /// </summary>
        /// <param name="rq"></param>
        /// <returns></returns>
        [API("SyncStockInSum")]
        FnResult<DyObject> UpdateOrderStockInFromOpen(SOARequestContext rq)
        {
            long appid = rq.RequestContext.GetOrDefault<long>("appid", -1);
            string srcData = rq.RequestContext.GetOrDefault<string>("opendata", "");
            if (!string.IsNullOrEmpty(srcData))
            {
                var data = XMLSetting.LoadFromStr(srcData);
                XMLSettingItem[] itms = data.All("Item");
                if (itms.Length > 0)
                {
                    DateTime utime = DateTime.Now;
                    var cmd = Host.ORM.DB.PG();
                    int max = 100;
                    for (int i = 0; i < itms.Length; i++)
                    {
                        XMLSettingItem itm = itms[i];
                        //根据原始入库明细更新订单进度
                        string srcmxid =itm.First("OrderMXID", false).Value;      //此入库数量指向的原始订单明细     
                        decimal totalStockIn = decimal.Parse(itm.First("TotalStockIn", false).Value);

                        var odmx= Host.ORM.DB.PG().Select<OrderMX>("@.id as ordermxid").As("om")
                                                  .Where("status").Uneq(BizObjLifeStatus.Aborted) //避免根据Openguid找到的是作废的旧订单明细
                                                  .And("iscurrentver").Eq(true)
                                                  .Join<BORelation>().As("r")
                                                  .Where("rtype").Eq("OrderMX-Opensrc")
                                                  .And("srcid").Eq("@[om.id]")
                                                  .Join<OpenOrderMX>().As("oom")
                                                  .Where("plateid").Eq("@[r.objid]")
                                                  .And("id").Eq(srcmxid)
                                                  .And("fromapp").Eq(appid.ToString())
                                                  .Query();
                        if (odmx.Count > 0)
                        {
                            LiberBizHelper.TradeSVC.ProcessTradeItem(ref cmd, "StockInSum", (long)odmx[0]["ordermxid"], totalStockIn, appid.ToString(), -1, true);
                        }
                        if (i > max)
                        {
                            max += 100;
                            var icrt = cmd.GO();
                            cmd = Host.ORM.DB.PG();
                        }
                    }
                    cmd.GO();
                    data.Dispose();

                    //汇总本次更新涉及到的订单，给相关人员发送通知，并更新交易总进度
                    var uporders = Host.ORM.DB.PG().Select<BORelation>("@.objid as orderid").As("r_order")
                                         .Where("rtype").Eq("Order-Item")
                                         .GroupBy("r_order.objid,tr.src_orderserial")
                                         .Join<TradeItemProcess>().As("op")
                                         .Where("ordermxid").Eq("@[r_order.srcid]")
                                         .And("createtime").BiggerOrEq(utime)
                                         .And("processtype").Eq("StockInSum")
                                         .And("status").Eq(BizObjLifeStatus.Completed)
                                         .Join<Trade>("@.src_orderserial").As("tr")
                                         .Where("id").Eq("@[r_order.objid]")
                                         .And("status").Uneq(BizObjLifeStatus.Aborted)  //避免根据Openguid找到的是作废的旧订单
                                         .Query();

                    var prctrade = Host.ORM.DB.PG() as PGSQLHelper;
                    int nmax = 100;
                    int n = 0;
                    foreach (var u in uporders)
                    {
                        long oid = (long)u["orderid"];
                        var buyer = LiberBizHelper.AcntSVC.GetUserByRelation(oid, "Order-Buyer");
                        var saler = LiberBizHelper.AcntSVC.GetUserByRelation(oid, "Order-Saler");
                        string odserial = u["src_orderserial"] == null ? u["idstr"].ToString() : u["src_orderserial"].ToString();

                        LiberBizHelper.TradeSVC.UpdateTradeProcess(ref prctrade, "StockInSum", oid,-1, appid.ToString());
                        
                        if (buyer.Count > 0&& buyer[0]["wxuser"].ToString()!="")
                        {
                            //通知买方采购员入库状态更新
                            DyObject wxmsg = new DyObject().Set("first", new DyObject().Set("value", "订单入库进度更新")
                                                                               .Set("color", "#3987c5"))
                                                   .Set("OrderSn", new DyObject().Set("value", odserial)
                                                                                 .Set("color", "#666666"))
                                                   .Set("OrderStatus", new DyObject().Set("value", "执行中")
                                                                                     .Set("color", "#3987c5"))
                                                   .Set("remark", new DyObject().Set("value", "订单入库状态已更新，请点击此消息查看详情")
                                                                                .Set("color", "#666666"));

                            LiberBizHelper.UserMsgSVC.InformWechat(Name, "OrderStockIn", buyer[0]["wxuser"].ToString(), oid, wxmsg);
                        }
                        if (saler.Count > 0&& saler[0]["wxuser"].ToString() != "")
                        {
                            //通知卖方销售人员入库状态更新
                            DyObject wxmsg = new DyObject().Set("first", new DyObject().Set("value", "订单入库进度更新")
                                                                                       .Set("color", "#3987c5"))
                                                           .Set("OrderSn", new DyObject().Set("value", odserial)
                                                                                         .Set("color", "#666666"))
                                                           .Set("OrderStatus", new DyObject().Set("value", "执行中")
                                                                                             .Set("color", "#3987c5"))
                                                           .Set("remark", new DyObject().Set("value", "买方已更新入库状态，请点击此消息查看详情")
                                                                                        .Set("color", "#666666"));
                            LiberBizHelper.UserMsgSVC.InformWechat(Name, "OrderStockIn", saler[0]["wxuser"].ToString(), oid, wxmsg);
                        }
                        n++;
                        if (n > nmax)
                        {
                            nmax += 100;
                            prctrade.GO();
                            prctrade = Host.ORM.DB.PG() as PGSQLHelper;
                        }
                    }
                    prctrade.GO();
                }
            }
            return FnResult<DyObject>.Sucess(null);
        }

        /// <summary>
        /// 同步订单的关闭(中止、重新激活)状态
        /// </summary>
        /// <param name="rq"></param>
        /// <returns></returns>
        [API("SyncClosedOrder")]
        FnResult<DyObject> UpdateClosedOrder(SOARequestContext rq)
        {
            long appid = rq.RequestContext.GetOrDefault<long>("appid", -1);
            string srcData = rq.RequestContext.GetOrDefault<string>("opendata", "");
            if (!string.IsNullOrEmpty(srcData))
            {
                var data = XMLSetting.LoadFromStr(srcData);
                XMLSettingItem[] itms = data.All("Item");
                if (itms.Length > 0)
                {
                    DateTime utime = DateTime.Now;
                    var cmd = Host.ORM.DB.PG();
                    int max = 100;
                    for (int i = 0; i < itms.Length; i++)
                    {
                        XMLSettingItem itm = itms[i];
                        string orderid = itm.First("OrderID", false).Value;
                        string oprtype = itm.First("OpreatType").Value;
                        string oprer = itm.First("Opreater").Value;
                        string remark = itm.First("Remark").Value;

                        cmd.Update<Order>().As("d")
                           .Set("status",oprtype== "CloseOrder"? BizObjLifeStatus.Completed:BizObjLifeStatus.Draft)
                           .Where("iscurrentver").Eq(true)
                           .And("status").Uneq(oprtype=="CloseOrder"?BizObjLifeStatus.Completed:BizObjLifeStatus.Draft)
                           .Join<BORelation>().As("r")
                           .Where("rtype").Eq("Order-Opensrc")
                           .And("srcid").Eq("@[d.id]")
                           .Join<OpenOrder>().As("oo")
                           .Where("id").Eq(orderid)
                           .And("plateid").Eq("@[r.objid]");

                        if (i > max)
                        {
                            max += 100;
                            var icrt = cmd.GO();
                            cmd = Host.ORM.DB.PG();
                        }
                    }
                    cmd.GO();
                    data.Dispose();

                    //对于重新激活的订单，重新发布
                    PublishOrder(false);
                }
            }
            return FnResult<DyObject>.Sucess(null);
        }

        #region 历史数据处理以后都不用API的方式，另外采用离线数据导入
        //[API("HistoryOpenPurchaseOrder")]
        //FnResult<DyObject> IniHistoryOpenOrder(SOARequestContext rq)
        //{
        //    string appid = rq.RequestContext.GetOrDefault<string>("appid", "");
        //    string srcData = rq.RequestContext.GetOrDefault<string>("opendata", "");
        //    DateTime bt = DateTime.Now;
        //    if (!string.IsNullOrEmpty(srcData))
        //    {
        //        var data = XMLSetting.LoadFromStr(srcData);
        //        XMLSettingItem[] itms = data.All("Item");
        //        try
        //        {
        //            CreateNewOrderByOpensrc(itms, appid);
        //        }
        //        catch(Exception ex)
        //        {

        //        }
        //        finally
        //        {
        //            data.Dispose();
        //        }
        //      }
        //      return FnResult<DyObject>.Sucess(null);
        //}

        //[API("HistoryOpenPurchaseOrderMX")]
        //FnResult<DyObject> IniHistoryOpenPurchaseOrderMX(SOARequestContext rq)
        //{
        //    string appid = rq.RequestContext.GetOrDefault<string>("appid", "");
        //    string srcData = rq.RequestContext.GetOrDefault<string>("opendata", "");
        //    if (!string.IsNullOrEmpty(srcData))
        //    {
        //        var data = XMLSetting.LoadFromStr(srcData);
        //        XMLSettingItem[] itms = data.All("Item");

        //        if (itms.Length > 0)
        //            {
        //                var cmd = Host.ORM.DB.PG();
        //                int max = 100;
        //                for (int i = 0; i < itms.Length; i++)
        //                {
        //                    XMLSettingItem itm = itms[i];
        //                    //保存原始订单明细
        //                    string id = itm.First("ID").Value;
        //                    string orderid = itm.First("OrderID").Value;
        //                    string name = itm.First("Name").Value;
        //                    string brand = itm.First("Brand").Value;
        //                    string model = itm.First("Model").Value;
        //                    string specification = itm.First("Specification").Value;
        //                    double count = double.Parse(itm.First("Count").Value);
        //                    string unit = itm.First("Unit").Value;
        //                    double price = double.Parse(itm.First("Price").Value);
        //                    decimal amount = decimal.Parse(itm.First("Amount").Value);
        //                    string memo = itm.First("Memo").Value;
        //                    string code = itm.First("Code").Value;
        //                    string fromapp = appid;

        //                    DyObject openmx = LiberBizHelper.TradeSVC.NewOpenPOMX(ref cmd, id, orderid, name, brand, model, specification, count, unit, price, amount, memo, fromapp, code);
        //                    DyObject odmx = LiberBizHelper.TradeSVC.CreateOrderMX(ref cmd, name, brand, model, count, unit, price, amount, memo, -1, (long)openmx["plateid"]);

        //                    if (i > max)
        //                    {
        //                        max += 100;
        //                        var icrt = cmd.GO();
        //                        cmd.Reset();
        //                        cmd = Host.ORM.DB.PG();
        //                    }
        //                }
        //                cmd.GO();
        //                data.Dispose();
        //            }

        //        //TODO：对于历史订单，不存在重复的GUID，可以用这种方式来批量更新平台订单明细所对应的订单
        //        Host.ORM.DB.PG().GO(@"INSERT INTO st_relation(rtype,createtime,updatetime,isdeleted,srcid,objid)
        //                          SELECT 'Order-Item',now(),now(),'false',a.id,f.id as orderid from at_ordermx as a
        //                          JOIN st_relation b
        //                          ON b.srcid=a.id
        //                          AND b.rtype='OrderMX-Opensrc'
        //                          JOIN at_openordermx c
        //                          ON c.plateid=b.objid
        //                          JOIN at_openorder d
        //                          ON d.id=c.orderid
        //                          AND d.iscurrentver=true
        //                          JOIN st_relation e
        //                          ON d.plateid=e.objid
        //                          AND e.rtype='Order-Opensrc'
        //                          JOIN at_order f
        //                          ON f.id=e.srcid
        //                          WHERE NOT EXISTS(SELECT b.srcid FROM st_relation b WHERE b.rtype='Order-Item' AND b.srcid=a.id)");

        //    }
        //    PublishOrder(false);
        //    return FnResult<DyObject>.Sucess(null);
        //}

        //[API("HistoryOpenPurchaseOrderStockSum")]
        //FnResult<DyObject> IniHistoryOpenPurchaseOrderStockSum(SOARequestContext rq)
        //{
        //    string appid = rq.RequestContext.GetOrDefault<string>("appid", "");
        //    string srcData = rq.RequestContext.GetOrDefault<string>("opendata", "");
        //    if (!string.IsNullOrEmpty(srcData))
        //    {
        //        var data = XMLSetting.LoadFromStr(srcData);
        //        XMLSettingItem[] itms = data.All("Item");
        //        if (itms.Length > 0)
        //        {
        //            DateTime utime = DateTime.Now;
        //            var cmd = Host.ORM.DB.PG();
        //            int max = 100;

        //            long tmpid = IdFactory.NewID();
        //            for (int i = 0; i < itms.Length; i++)
        //            {
        //                XMLSettingItem itm = itms[i];
        //                //根据原始入库明细更新订单进度
        //                string srcmxid = itm.First("OrderMXID", false).Value;
        //                decimal totalStockIn = decimal.Parse(itm.First("TotalStockIn", false).Value);

        //                //TODO：先用dataSrc记录对应的原始订单明细id，并指定非覆盖模式
        //                LiberBizHelper.TradeSVC.ProcessTradeItem(ref cmd, "StockInSum", tmpid, totalStockIn, srcmxid, -1, false);
        //                if (i > max)
        //                {
        //                    max += 100;
        //                    var icrt = cmd.GO();
        //                    cmd = Host.ORM.DB.PG();
        //                }
        //            }
        //            cmd.GO();

        //            //TODO:批量将旧的记录设为历史版本,将本次插入的记录ordermxid指向openordermxid所指向的真正ordermxid
        //            var up = Host.ORM.DB.PG().Update<TradeItemProcess>()
        //                                   .Set("status", BizObjLifeStatus.Aborted)
        //                                   .Where("").Exist(Host.ORM.DB.PG().Select<TradeItemProcess>().As("cop")
        //                                                                    .Where("processtype").Eq("StockInSum")
        //                                                                    .And("ordermxid").Uneq(tmpid)
        //                                                                    .Join<TradeItemProcess>().As("precop")
        //                                                                    .Where("datasrc").Eq("@[cop.datasrc]")
        //                                                                    )
        //                                  .GO();

        //            var uc = Host.ORM.DB.PG().Update<TradeItemProcess>().As("up")
        //                                     .Set("ordermxid", Host.ORM.DB.PG().Select<OrderMX>("@.id").As("om")
        //                                                                    .Join<BORelation>().As("r")
        //                                                                    .Where("rtype").Eq("OrderMX-Opensrc")
        //                                                                    .And("srcid").Eq("@[om.id]")
        //                                                                    .Join<OpenOrderMX>().As("oom")
        //                                                                    .Where("plateid").Eq("@[r.objid]")
        //                                                                    .And("id").Eq("@[up.datasrc]"))
        //                                     .Where("ordermxid").Eq(tmpid)
        //                                     .And("processtype").Eq("StockInSum")
        //                                     .GO();

        //            data.Dispose();
        //        }
        //    }
        //    return FnResult<DyObject>.Sucess(null);
        //}
        #endregion

        [API("QueryReceipts")]
        FnResult<DyObject> QueryReceipts(SOARequestContext rq)
        {
            long uid = rq.RequestContext.GetOrDefault<long>("uid", -1);
            bool onlyCter = rq.RequestContext.GetOrDefault<bool>("onlymine", true);
            string status = rq.RequestContext.GetOrDefault<string>("status", "Active");
            string flag = rq.RequestContext.GetOrDefault<string>("flag", "");
            string dlvDate = rq.RequestContext.GetOrDefault<string>("dlvDate", "all");


            PGSQLHelper cmd = Host.ORM.DB.PG().Select<DeliveryBill>().As("a") as PGSQLHelper;
            cmd.Where("isdeleted").Eq(false);

            BizObjLifeStatus st = status.ToBizObjLifeStatus();
            if (st != BizObjLifeStatus.Unknow)
            {
                cmd.And("status").Eq(status);
            }

            switch (dlvDate)
            {
                case "all":
                    break;
                case "thisWeek":
                    DateTime startWeek = DateTime.Today.AddDays(1 - Convert.ToInt32(DateTime.Today.DayOfWeek.ToString("d")));  //本周周一  
                    cmd.And("createtime").BiggerOrEq(startWeek);
                    break;
                case "thisMonth":
                    DateTime startMonth = DateTime.Today.AddDays(1 - DateTime.Today.Day);  //本月月初  
                    cmd.And("createtime").BiggerOrEq(startMonth);
                    break;
            }
            cmd.Join<BORelation>("@.objid as orderid").As("od")
               .Where("srcid").Eq("@[a.id]")
               .And("rtype").Eq("Order-Delivery")
               .Join<BORelation>("@.srcid as deptid").As("rd")
               .Where("objid").Eq("@[od.objid]")
               .And("rtype").Eq("Order-Clientdept");

            if (onlyCter)
            {
                cmd.Join<Trade>().As("tr")
                   .Where("consigneeid").Eq(uid)
                   .And("id").Eq("@[od.objid]");
            }
            else
            {
                LiberBizHelper.OrgSVC.InUpOrgTree(ref cmd, "@[rd.srcid]", uid);
            }

            var data = cmd.Query();
            foreach (var d in data)
            {
                var od = Host.ORM.DB.PG().Select<Trade>().As("t")
                                       .Join<BORelation>().As("r")
                                       .Where("rtype").Eq("Order-Delivery")
                                       .And("srcid").Eq((long)d["id"])
                                       .And("objid").Eq("@[t.id]")
                                       .Limit(1)
                                       .Query();
                if (od.Count > 0)
                {
                    d.Set("order", od[0]);
                }
            }

            return FnResult<DyObject>.Sucess(DyObject.FromObjList("Deliveries", data));
        }

        void CreateNewOrderByOpensrc(XMLSettingItem[] itms,string appid)
        {
            int max = 100;  //每批次最多处理100份原始订单
            PGSQLHelper cmd = Host.ORM.DB.PG();
            Regex mphoneRx = new Regex(@"[1]+[3|4|5|7|8]+\d{9}");  //用于提取手机号码的正则
            DateTime bt = DateTime.Now;
            for (int i = 0, n = itms.Length; i < n; i++)
            {
                XMLSettingItem itm = itms[i];
                string id = itm.First("ID").Value;
                string preid = itm.First("PreID").Value;
                string serial = itm.First("Serial").Value;
                string version = itm.First("Version").Value;  //版本号是必须的吗？
                string invoiceheading = itm.First("InvoiceHeading").Value;
                string client = itm.First("Client").Value;
                string buyer = itm.First("Buyer").Value;
                string buyerphone = itm.First("BuyerPhone").Value;
                string supplier = itm.First("Supplier").Value;
                string saler = itm.First("Saler").Value;
                string salerphone = itm.First("SalerPhone").Value;
                DateTime deliverydate = DateTime.Parse(itm.First("DeliveryDate").Value);
                string deliveryaddress = itm.First("DeliveryAddress").Value;
                string contractno = itm.First("ContractNO").Value;
                string consignee = itm.First("Consignee").Value;
                string consigneephone = itm.First("ConsigneePhone").Value;
                string deliverymode = itm.First("DeliveryMode").Value;
                string settlement = itm.First("Settlement").Value;
                string qualityguarantee = itm.First("QualityGuarantee").Value;
                string memo = itm.First("Memo").Value;
                decimal amount = Numberic.TryGetDecimal(itm.First("Amount").Value, 0);              
                string receipt = itm.First("Receipt").Value;
                DateTime orderdate = DateTime.Parse(itm.First("OrderDate").Value);
                DateTime publishtime = DateTime.Parse(itm.First("PublishTime").Value);
                decimal taxrate = Numberic.TryGetDecimal(itm.First("TaxRate").Value,0);
                string invoicetype = itm.First("InvoiceType").Value;
                string invoicemx = itm.First("InvoiceMX").Value;
                string constructor = itm.First("Constructor").Value;
                string subconstructor = itm.First("SubConstructor").Value;

                //判断是否为改单
                var IsOldOrder = Host.ORM.DB.PG().Select<OpenOrder>("@.plateid").As("oo")
                                             .Where("id").Eq(id)
                                             .Limit(1)
                                             .Join<BORelation>().As("r")
                                             .Where("rtype").Eq("Order-Opensrc")
                                             .And("objid").Eq("@[oo.plateid]")
                                             .Join<Order>("@.id as orderid").As("od")
                                             .Where("id").Eq("@[r.srcid]")
                                             .And("iscurrentver").Eq(true)  //判断所改的单在平台上关联的最新订单
                                             .Query();
                if (IsOldOrder.Count == 0)
                {
                    #region 新订单
                    //创建新订单
                    DyObject opnd = LiberBizHelper.TradeSVC.NewOpenPO(ref cmd, appid, id, preid, serial, version, invoiceheading, client, buyer, buyerphone, supplier, saler, salerphone, deliverydate, deliveryaddress, contractno, consignee, consigneephone, deliverymode, settlement, qualityguarantee, memo, amount, receipt, orderdate, publishtime, taxrate, invoicetype, invoicemx,constructor, subconstructor);
                    DyObject nd = LiberBizHelper.TradeSVC.CreateOrder(ref cmd, invoiceheading, amount, taxrate, deliverydate, settlement, deliverymode, qualityguarantee, memo, invoicetype, invoicemx, (long)opnd["plateid"]);
                    long oid = (long)nd["id"];

                    //创建订单明细
                    if (itm.First("OrderItems").First("ItemCount").Value != "0")
                    {
                        var mx = itm.First("OrderItems").First("Items").All("OrderItem", false);
                        foreach (var m in mx)
                        {
                            string itmid = m.First("ID").Value;
                            string orderid = m.First("OrderID").Value;
                            string name = m.First("Name").Value;
                            string brand = m.First("Brand").Value;
                            string model = m.First("Model").Value;
                            string specification = m.First("Specification").Value;
                            double count = double.Parse(m.First("Count").Value);
                            string unit = m.First("Unit").Value;
                            double price = double.Parse(m.First("Price").Value);
                            decimal itmamount = decimal.Parse(m.First("Amount").Value);
                            string itmmemo = m.First("Memo").Value;
                            string code = m.First("Code").Value;
                            string fromapp = appid;

                            DyObject openmx = LiberBizHelper.TradeSVC.NewOpenPOMX(ref cmd, itmid, orderid, name, brand, model, specification, count, unit, price, itmamount, itmmemo, fromapp, code);
                            DyObject odmx = LiberBizHelper.TradeSVC.CreateOrderMX(ref cmd, name, brand, model, count, unit, price, itmamount, itmmemo, oid, (long)openmx["plateid"]);
                        }
                    }

                    var bphone = mphoneRx.Match(buyerphone).Groups;
                    string sphone = mphoneRx.Match(salerphone).Groups[0].Value;

                    //处理采购员和甲方关系（1.用ERP里用户所属公司）
                    var buyerAcnt = LiberBizHelper.AcntSVC.GetPeopleAcnt(client, buyer, bphone.Count > 0 ? bphone[0].Value : "no phone");
                    if (buyerAcnt == null && mphoneRx.Match(buyerphone).Groups.Count > 1)
                    {
                        buyerAcnt = LiberBizHelper.AcntSVC.GetPeopleAcnt(client, buyer, bphone[1].Value);
                    }
                    if (buyerAcnt != null && buyerAcnt.Has("CompanyOrg"))
                    {
                        BORelation rbuyer = new BORelation("Order-Buyer", (long)buyerAcnt["id"], oid);
                        BORelation rclient = new BORelation("Order-Client", (long)((DyObject)buyerAcnt["CompanyOrg"])["id"], oid);
                        var bdept = LiberBizHelper.OrgSVC.GetAcntDept((long)buyerAcnt["id"]);
                        BORelation rbuyer_dept = new BORelation("Order-Clientdept", (long)bdept["id"], oid);
                        cmd.Insert(rbuyer);
                        cmd.Insert(rclient);
                        cmd.Insert(rbuyer_dept);
                    }
                    else if (client.Length > 0)
                    {
                        //TODO:没有采购员，根据采购单位名称将订单放在对应的公司下
                        var bdept = LiberBizHelper.OrgSVC.FindRealCompany(client);
                        if (bdept != null)
                        {
                            BORelation rclient = new BORelation("Order-Client", (long)bdept["orgid"], oid);
                            BORelation rbuyer_dept = new BORelation("Order-Clientdept", (long)bdept["orgid"], oid);
                            cmd.Insert(rclient);
                            cmd.Insert(rbuyer_dept);
                        }
                    }
                    else if (invoiceheading.Length > 0)
                    {
                        //TODO:没有采购员，没有客户，根据发票抬头将订单放在对应的公司下
                        var bdept = LiberBizHelper.OrgSVC.FindRealCompany(invoiceheading);
                        if (bdept != null)
                        {
                            BORelation rclient = new BORelation("Order-Client", (long)bdept["orgid"], oid);
                            BORelation rbuyer_dept = new BORelation("Order-Clientdept", (long)bdept["orgid"], oid);
                            cmd.Insert(rclient);
                            cmd.Insert(rbuyer_dept);
                        }
                    }
                    else
                    {

                    }

                    //处理销售员和乙方单位
                    var salerAcnt = LiberBizHelper.AcntSVC.GetPeopleAcnt(supplier, saler, sphone);
                    if (salerAcnt != null && salerAcnt.Has("CompanyOrg"))
                    {
                        BORelation rsaler = new BORelation("Order-Saler", (long)salerAcnt["id"], oid);
                        BORelation rsupplier = new BORelation("Order-Supplier", (long)((DyObject)salerAcnt["CompanyOrg"])["id"], oid);
                        var sdept = LiberBizHelper.OrgSVC.GetAcntDept((long)salerAcnt["id"]);
                        BORelation rsaler_dept = new BORelation("Order-Supplierdept", (long)sdept["id"], oid);
                        cmd.Insert(rsaler);
                        cmd.Insert(rsupplier);
                        cmd.Insert(rsaler_dept);
                    }
                    else if (!string.IsNullOrWhiteSpace(supplier))
                    {
                        var sdept = LiberBizHelper.OrgSVC.FindRealCompany(supplier);
                        if (sdept != null)
                        {
                            BORelation rsupplier = new BORelation("Order-Supplier", (long)sdept["orgid"], oid);
                            BORelation rsaler_dept = new BORelation("Order-Supplierdept", (long)sdept["orgid"], oid);
                            cmd.Insert(rsupplier);
                            cmd.Insert(rsaler_dept);

                            if (!string.IsNullOrEmpty(salerphone))
                            {
                                //TODO:只有手机号，则用短信推荐其来平台注册账号
                            }
                        }
                    }
                    else
                    {

                    }

                    //处理收货人
                    if (consignee.Length > 0)
                    {
                        string c = consignee.Split('/', ',', '（', '，', ';', '；', '(', '[', '-')[0];
                        string cp = mphoneRx.Match(consigneephone).Groups[0].Value;
                        //收货人只按姓名+手机号匹配
                        var cacnt = LiberBizHelper.AcntSVC.GetPeopleAcnt("", c, cp);
                        if (cacnt != null)
                        {
                            BORelation rcnsign = new BORelation("Order-Consignee", (long)cacnt["id"], oid);
                            cmd.Insert(rcnsign);
                        }
                    }

                    //检查是否有关联的文档已上传
                    var docName = id.ToString() + "%ef%bc%9fOrder-Purchasecontract%ef%bc%9f" + version + ".pdf";
                    var fm = Host.ORM.DB.PG().Select<FileMeta>("@.id").As("fm")
                                    .Where("filename").Eq(docName)
                                    .Query();
                    if (fm.Count > 0)
                    {
                        foreach (var f in fm)
                        {
                            long fid = (long)f["id"];
                            BORelation of = new BORelation("Order-Attachment", fid, oid);
                            cmd.Insert(of);
                        }
                    }

                    #endregion
                }
                else
                {
                    long oid = (long)IsOldOrder[0]["orderid"]; //旧单ID
                    long oldOpenid = (long)IsOldOrder[0]["plateid"]; //旧单关联Openorderid
                    
                    #region 改单
                    //1.复制旧单数据
                    LiberBizHelper.TradeSVC.CopyOrder(oid);

                    //作废原单关联的待办
                    LiberBizHelper.TODOSvc.AbortTODO(oid);

                    //2.保存抓取结果，并更新旧单数据
                    DyObject opnd = LiberBizHelper.TradeSVC.NewOpenPO(ref cmd, appid, id, preid, serial, version, invoiceheading, client, buyer, buyerphone, supplier, saler, salerphone, deliverydate, deliveryaddress, contractno, consignee, consigneephone, deliverymode, settlement, qualityguarantee, memo, amount, receipt, orderdate, publishtime, taxrate, invoicetype, invoicemx,constructor,subconstructor);
                    LiberBizHelper.TradeSVC.ResetOrder(ref cmd,oid,invoiceheading, amount, taxrate, deliverydate, settlement, deliverymode, qualityguarantee, memo, invoicetype, invoicemx,(long)opnd["plateid"]);

                    //3.更新订单明细
                    if (itm.First("OrderItems").First("ItemCount").Value != "0")
                    {
                        var mx = itm.First("OrderItems").First("Items").All("OrderItem", false);
                        foreach (var m in mx)
                        {
                            string itmid = m.First("ID").Value;
                            string orderid = m.First("OrderID").Value;
                            string name = m.First("Name").Value;
                            string brand = m.First("Brand").Value;
                            string model = m.First("Model").Value;
                            string specification = m.First("Specification").Value;
                            double count = double.Parse(m.First("Count").Value);
                            string unit = m.First("Unit").Value;
                            double price = double.Parse(m.First("Price").Value);
                            decimal itmamount = decimal.Parse(m.First("Amount").Value);
                            string itmmemo = m.First("Memo").Value;
                            string code = m.First("Code").Value;
                            string fromapp = appid;

                            var premx = Host.ORM.DB.PG().Select<OrderMX>().As("om")
                                                        .Limit(1)
                                                        .Join<BORelation>().As("ro")
                                                        .Where("rtype").Eq("OrderMX-Opensrc")
                                                        .And("srcid").Eq("@[om.id]")
                                                        .Join<OpenOrderMX>().As("oomx")
                                                        .Where("plateid").Eq("@[ro.objid]")
                                                        .And("id").Eq(itmid)
                                                        .Query();

                            DyObject openmx = LiberBizHelper.TradeSVC.NewOpenPOMX(ref cmd, itmid, orderid, name, brand, model, specification, count, unit, price, itmamount, itmmemo, fromapp, code);
                            LiberBizHelper.TradeSVC.ResetOrderMX(ref cmd, (long)(premx[0]["id"]), name, brand, model, count, unit, price, itmamount, itmmemo, (long)openmx["plateid"]);
                        }

                        //删除原有附件关系
                        cmd.Del<BORelation>()
                           .Where("rtype").Eq("Order-Attachment")
                           .And("objid").Eq(oid);

                        //检查是否有关联的文档已上传
                        var docName = id.ToString() + "%ef%bc%9fOrder-Purchasecontract%ef%bc%9f" + version + ".pdf";
                        var fm = Host.ORM.DB.PG().Select<FileMeta>("@.id").As("fm")
                                        .Where("filename").Eq(docName)
                                        .Query();
                        if (fm.Count > 0)
                        {
                            foreach (var f in fm)
                            {
                                long fid = (long)f["id"];
                                BORelation of = new BORelation("Order-Attachment", fid, oid);
                                cmd.Insert(of);
                            }
                        }
                    }
                    #endregion
                }

                //防止批次量超过SQL限制
                if (i > max)
                {
                    max += 100;
                    var icrt = cmd.GO();
                    cmd = Host.ORM.DB.PG();
                }
            }
            cmd.GO();
        }

        /// <summary>
        /// 发布订单给卖方(必须至少具备saler或supplierdept)
        /// </summary>
        void PublishOrder(bool requireConfirm=true)
        {
            //根据是否匹配到足够信息更新订单状态
            if (requireConfirm)
            {
                LiberBizHelper.TradeSVC.UpdateOrder()
                                             .Set("status", BizObjLifeStatus.Pending)
                                             .Where("id").In(Host.ORM.DB.PG().Select<Order>("id").As("b")
                                                                              .Where("status").Eq(BizObjLifeStatus.Draft)
                                                                              .And("isdeleted").Eq(false)
                                                                              .Join<BORelation>().As("r2")
                                                                              .Where("rtype").Eq("Order-Saler")
                                                                              .Or("rtype",true).Eq("Order-Supplierdept")
                                                                              .And("objid").Eq("@[b.id]")
                                                            )
                                             .GO();

                //对于新发布订单，为卖方联系人创建待办并发送微信消息
                var newod = Host.ORM.DB.PG().Select<Trade>().As("a")
                                            .Where("status").Eq(BizObjLifeStatus.Pending)
                                            .And("").NotExists(Host.ORM.DB.PG().Select<TODO>("1")
                                                                               .Where("objid").Eq("@[a.id]")
                                                                               .And("todotype").Eq("ConfirmOrder")
                                                                               .And("status").Eq(BizObjLifeStatus.Active))
                                            .Query();
                var todo = Host.ORM.DB.PG();
                foreach (var od in newod)
                {
                    //创建ConfirmOrder待办
                    long oid = (long)od["id"];
                    long saler =od["saler_id"].ToString()==""?-1:(long)od["saler_id"];

                    LiberBizHelper.TODOSvc.New(ref todo, "ConfirmOrder", oid, DateTime.Now, DateTime.MaxValue, saler, -1, "");
                    
                    //创建通知消息
                    var salerAcnt = LiberBizHelper.AcntSVC.GetAccountInfo(saler,true);
                    if (salerAcnt.IsPositive && salerAcnt.Data["wxuser"].ToString() != "")
                    {
                        string serial = od["id"].ToString();
                        if (od["src_orderserial"].ToString() != "")
                        {
                            serial = od["src_orderserial"].ToString();
                            if (od["src_orderversion"].ToString() != "")
                            {
                                serial += "[" + od["src_orderversion"].ToString() + "]";
                            }
                        }

                        DyObject wxmsg = new DyObject().Set("first", new DyObject().Set("value", "您收到一份新订单")
                                                                       .Set("color", "#3987c5"))
                                                       .Set("keyword1", new DyObject().Set("value", serial) //订单编号
                                                                                     .Set("color", "#666666"))
                                                       .Set("keyword2", new DyObject().Set("value", od["amount"].ToString())  //订单金额
                                                                                         .Set("color", "#3987c5"))
                                                       .Set("keyword3", new DyObject().Set("value", od["client_realname"].ToString())  //采购单位
                                                                                         .Set("color", "#3987c5"))
                                                       .Set("keyword4", new DyObject().Set("value", od["buyer"].ToString() + "[" + od["buyer_phone"].ToString() + "]")  //联系人
                                                                                         .Set("color", "#3987c5"))
                                                       .Set("keyword5", new DyObject().Set("value", DateTime.Parse(od["deliverydate"].ToString()).ToShortDateString())  //交货日期
                                                                                         .Set("color", "#3987c5"))
                                                       .Set("remark", new DyObject().Set("value", "订单已发布至天联云协同平台，请查看订单详情并尽快确认")
                                                                                    .Set("color", "#666666"));
                        LiberBizHelper.UserMsgSVC.InformWechat(Name, "NewSaleOrder", salerAcnt.Data["wxuser"].ToString(), oid, wxmsg);
                    }
                }
                todo.GO();
            }
            else
            {
                //对于注册之前的订单，匹配之后默认为激活状态，无需再确认
                LiberBizHelper.TradeSVC.UpdateOrder()
                                             .Set("status", BizObjLifeStatus.Active)
                                             .Where("id").In(Host.ORM.DB.PG().Select<Order>("id").As("b")
                                                                              .Where("status").Eq(BizObjLifeStatus.Draft)
                                                                              .And("iscurrentver").Eq(true)
                                                                              .Join<BORelation>().As("r2")
                                                                              .Where("rtype").Eq("Order-Saler")
                                                                              .Or("rtype",true).Eq("Order-Supplierdept")
                                                                              .And("objid").Eq("@[b.id]")
                                                              )
                                             .GO();
                
                //2016-08-06:对于历史订单，不再创建待办记录
                //对于历史订单，为卖方联系人创建已完成的待办记录，但不发送消息
                //var historyod = Host.ORM.DB.PG().Select<Trade>().As("a")
                //                                .Where("status").Eq(BizObjLifeStatus.Active)
                //                                .And("[t.id]").IsNULL()
                //                                .LeftJoin<TODO>().As("t")
                //                                .Where("objid").Eq("@[a.id]")
                //                                .And("todotype").Eq("ConfirmOrder")
                //                                .Or("todotype",true).Eq("ReconfirmOrder")
                //                                .Query();

                //var todo = Host.ORM.DB.PG();
                //var max = 200;
                //var ci = 0;
                //foreach (var od in historyod)
                //{
                //    if (ci == max)
                //    {
                //        max += 200;
                //        todo.GO();
                //        todo = Host.ORM.DB.PG();
                //    }
                //    //如果有匹配到销售员，创建ConfirmOrder待办，并立刻完成
                //    if (od["saler_id"].ToString().Length > 0)
                //    {
                //        long oid = (long)od["id"];
                //        long saler = (long)od["saler_id"];
                //        LiberBizHelper.TODOSvc.New(ref todo, "ConfirmOrder", oid, DateTime.Now, DateTime.MaxValue, (long)od["saler_id"], -1, "");
                //        LiberBizHelper.TODOSvc.CompleteTODO(ref todo, "ConfirmOrder", oid, "历史订单自动确认");
                //        ci++;
                //    }
                //}
                //todo.GO();
            }
            
        }

        void TryMatchAcntOrder(long acnt)
        {
            //针对指定账号，尝试为其匹配订单
            var usr = LiberBizHelper.AcntSVC.GetAccountInfo(acnt);
            if (usr.IsPositive)
            {
                string uname = usr.Data["realname"].ToString();
                string uphone = usr.Data["mphone"].ToString();
                List<DyObject> ucompnys = LiberBizHelper.OrgSVC.GetAcntBelongOrgs(acnt, true);
                Dictionary<string, long> ucompanyDic = new Dictionary<string, long>();

                //TODO：要改为获取用户在订单指定公司下的部门，而非其主岗所属部门（规则变化，一个人在一个公司下有一个主岗，而非全局一个主岗）
                DyObject udetp = LiberBizHelper.OrgSVC.GetAcntDept(acnt);

                foreach(var d in ucompnys)
                {
                    //2016-08-20:ZJArcher-这里要拿的是公司对应的组织架构ID，而非公司认证记录ID
                    ucompanyDic.Add(d["realname"].ToString(), (long)d["id"]);
                }

                //获取所有需要匹配的交易
                var ods_nomatch= LiberBizHelper.TradeSVC.GetOrder(-1, -1, -1, -1, "a")
                                                        .And("status").Uneq(BizObjLifeStatus.Aborted)
                                                        .And("src_buyer").Eq(uname)
                                                        .Or("src_saler",true).Eq(uname)
                                                        .Or("src_consignee",true).Like('%'+uname+ '%')
                                                        .Query();
                //Regex mphoneRx = new Regex(@"[1]+[3|4|5|7|8]+\d{9}");  //用于提取手机号码的正则
   
                foreach(var od in ods_nomatch)
                {
                    var cmd = Host.ORM.DB.PG();
                    long orderid = (long)od["id"];
          
                    //匹配采购员
                    if(string.IsNullOrEmpty(od["buyer"].ToString())&& od["src_buyer"].ToString()==uname&& ucompanyDic.ContainsKey(od["src_client"].ToString())&&od["src_buyerphone"].ToString().IndexOf(uphone)>=0)
                    {
                        BORelation rbuyer = new BORelation("Order-Buyer", acnt, orderid);
                        BORelation rclient = new BORelation("Order-Client", (long)ucompanyDic[od["src_client"].ToString()], orderid);
                        BORelation rbuyer_dept = new BORelation("Order-Clientdept", (long)udetp["id"], orderid);
                        cmd.Del<BORelation>().Where("objid").Eq(orderid)
                                                 .And("rtype").Eq("Order-Client")
                                                 .Or("rtype", true).Eq("Order-Clientdept");
                        cmd.Insert(rbuyer);
                        cmd.Insert(rclient);
                        cmd.Insert(rbuyer_dept);
                    }

                    //匹配销售员
                    if (string.IsNullOrEmpty(od["saler"].ToString()) && od["src_saler"].ToString() == uname && ucompanyDic.ContainsKey(od["src_supplier"].ToString())&&od["src_salerphone"].ToString().IndexOf(uphone)>=0)
                    {
                        BORelation rsaler = new BORelation("Order-Saler", acnt, orderid);
                        BORelation rsupplier = new BORelation("Order-Supplier", (long)ucompanyDic[od["src_supplier"].ToString()], orderid);
                        BORelation rsaler_dept = new BORelation("Order-Supplierdept", (long)udetp["id"], orderid);
                        cmd.Del<BORelation>().Where("objid").Eq(orderid)
                                                 .And("rtype").Eq("Order-Supplier")
                                                 .Or("rtype", true).Eq("Order-Supplierdept");
                        cmd.Insert(rsaler);
                        cmd.Insert(rsupplier);
                        cmd.Insert(rsaler_dept);
                    }
                   

                    //收货人只按姓名+手机号匹配
                    if (string.IsNullOrEmpty(od["consignee"].ToString()) && od["src_consignee"].ToString().Split('/', ',', '（', '，', ';', '；', '(', '[', '-')[0] == uname&& od["src_consigneephone"].ToString().IndexOf(uphone)>=0)
                    {
                        BORelation rconsignee = new BORelation("Order-Consignee", acnt, orderid);
                        cmd.Insert(rconsignee);
                    }                 
                    cmd.GO();
                }
            }
        }

        void TryMatchCompanyOrder(string companyname,long compnorg)
        {
            //匹配卖方公司
            var ods_supplier = LiberBizHelper.TradeSVC.GetOrder(-1, -1, -1, -1, "a")
                                                        .And("status").Uneq(BizObjLifeStatus.Aborted)
                                                        .And("src_supplier").Eq(companyname)
                                                        .And("supplier_id").IsNULL()
                                                        .Query();
            var cmd = Host.ORM.DB.PG();
            var supplier = LiberBizHelper.OrgSVC.FindRealCompany(companyname);
            if (supplier != null)
            {
                foreach (var od in ods_supplier)
                {
                    long orderid = (long)od["id"];

                    BORelation rsupplier = new BORelation("Order-Supplier", (long)supplier["orgid"], orderid);
                    BORelation rsaler_dept = new BORelation("Order-Supplierdept", (long)supplier["orgid"], orderid);
                    cmd.Insert(rsupplier);
                    cmd.Insert(rsaler_dept);

                    //如果创建人即订单销售员，再创建Order-Saler关系
                    if (!string.IsNullOrEmpty(supplier["creater"].ToString())&& supplier["creater"].ToString() == od["src_saler"].ToString())
                    {
                        BORelation rsaler = new BORelation("Order-Saler", (long)supplier["createrid"], orderid);
                        cmd.Insert(rsaler);
                    }
                }
            }

            cmd.GO();


            //匹配买方公司
            var ods_clnt = LiberBizHelper.TradeSVC.GetOrder(-1, -1, -1, -1, "a")
                                                        .And("status").Uneq(BizObjLifeStatus.Aborted)
                                                        .And("src_client").Eq(companyname)
                                                        .Or("invoiceheading",true).Eq(companyname)
                                                        .And("client_id").IsNULL()     
                                                        .Query();
            cmd.Reset();
            cmd = Host.ORM.DB.PG();
            var clnt = LiberBizHelper.OrgSVC.FindRealCompany(companyname);
            if (clnt != null)
            {
                foreach (var od in ods_clnt)
                {
                    long orderid = (long)od["id"];
                    BORelation rclnt = new BORelation("Order-Client", (long)clnt["orgid"], orderid);
                    BORelation rclnt_dept = new BORelation("Order-Clientdept", (long)clnt["orgid"], orderid);
                    cmd.Insert(rclnt);
                    cmd.Insert(rclnt_dept);

                    //如果创建人即订单采购，再创建Order-Buyer关系
                    if (!string.IsNullOrEmpty(clnt["creater"].ToString()) && clnt["creater"].ToString() == od["src_buyer"].ToString())
                    {
                        BORelation rbuyer = new BORelation("Order-Buyer", (long)clnt["createrid"], orderid);
                        cmd.Insert(rbuyer);
                    }
                }
            }

            cmd.GO();
        }
    }
}
